﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ConfeccionesJR.Entites;
using ConfeccionesJR.BussinesLogic;
using Microsoft.Practices.Unity;

namespace ConfeccionesJR.UI
{
    public partial class frmCredito : Form
    {
        [Dependency]
        public ICreditoBL creditoBL { get; set; }
        
        [Dependency]
        public IPagoBL pagoBL { get; set; }

        [Dependency]
        public IVentaBL ventaBL { get; set; }

        [Dependency]
        public IProductoBL prodBL { get; set; }

        [Dependency]
        public IImpuestoBL impBL { get; set; }

        [Dependency]
        public IDetalleCreditoBL detalleCredBL { get; set; }

        public frmCredito()
        {
            InitializeComponent();
            this.BuildUp();
        }

        float f_HeightRatio = new float();
        float f_WidthRatio = new float();

        public void ResizeForm(Form ObjForm, int DesignerHeight, int DesignerWidth)
        {
            #region Code for Resizing and Font Change According to Resolution

            int i_StandardHeight = DesignerHeight;
            int i_StandardWidth = DesignerWidth;
            int i_PresentHeight = Screen.PrimaryScreen.Bounds.Height - 65;
            int i_PresentWidth = Screen.PrimaryScreen.Bounds.Width - 245;
            f_HeightRatio = (float)((float)i_PresentHeight / (float)i_StandardHeight);
            f_WidthRatio = (float)((float)i_PresentWidth / (float)i_StandardWidth);
            //ObjForm.AutoScaleMode = AutoScaleMode.None;
            ObjForm.AutoScaleMode = AutoScaleMode.Dpi;
            ObjForm.Scale(new SizeF(f_WidthRatio, f_HeightRatio));
            foreach (Control c in ObjForm.Controls)
            {
                if (c.HasChildren)
                {
                    ResizeControlStore(c);
                }
                else
                {
                    c.Font = new Font(c.Font.FontFamily, c.Font.Size * f_HeightRatio, c.Font.Style, c.Font.Unit, ((byte)(0)));
                }
            }
            ObjForm.Font = new Font(ObjForm.Font.FontFamily, ObjForm.Font.Size * f_HeightRatio, ObjForm.Font.Style, ObjForm.Font.Unit, ((byte)(0)));
            #endregion
        }

        private void ResizeControlStore(Control objCtl)
        {
            #region

            if (objCtl.HasChildren)
            {
                foreach (Control cChildren in objCtl.Controls)
                {
                    if (cChildren.HasChildren)
                    {
                        ResizeControlStore(cChildren);
                    }
                    else
                    {
                        cChildren.Font = new Font(cChildren.Font.FontFamily, cChildren.Font.Size * f_HeightRatio, cChildren.Font.Style, cChildren.Font.Unit, ((byte)(0)));
                    }
                }
                objCtl.Font = new Font(objCtl.Font.FontFamily, objCtl.Font.Size * f_HeightRatio, objCtl.Font.Style, objCtl.Font.Unit, ((byte)(0)));
            }
            else
            {
                objCtl.Font = new Font(objCtl.Font.FontFamily, objCtl.Font.Size * f_HeightRatio, objCtl.Font.Style, objCtl.Font.Unit, ((byte)(0)));
            }
            #endregion
        }

        private void frmCredito_Load(object sender, EventArgs e)
        {
            
            //this.ResizeForm(this, 700, 1036); 

            dateTimePicker1.Enabled = false;
            dateTimePicker2.Enabled = false;
            ReiniciarFechas();
            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditos();
        }
        
        private void ReiniciarFechas()
        {
            dateTimePicker1.Value = DateTime.Now.Date;
            var fec2 = dateTimePicker1.Value.Date;
            dateTimePicker2.Value = fec2.AddDays(1);
        }

        private void LoadCreditos()
        {
            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditos();
            var currentCredito = cREDITOBindingSource.Current as CREDITO;
            if (currentCredito != null)
            {
                dETALLE_CREDITOBindingSource.DataSource = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);
                dETALLEPAGOesBindingSource.DataSource = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);
            }

        }

        private void cREDITODataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //var currentCredito = cREDITOBindingSource.Current as CREDITO;

            //if (currentCredito != null)
            //{
            //    var _detalles = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);
            //    dETALLE_CREDITOBindingSource.DataSource = _detalles;

            //    var _pagos = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);
            //    dETALLEPAGOesBindingSource.DataSource = _pagos;

            //    decimal saldoFavor = 0;
            //    decimal totalCredito = 0;

            //    if (_pagos != null)
            //    {
            //        var totalPagos = _pagos.Sum(p => p.Monto);
            //        var newTotalPagos = Math.Round(totalPagos, 2);
            //        lblTotalPagos.Text = newTotalPagos.ToString();
            //    }

            //    if (_detalles != null)
            //    {
            //        totalCredito = _detalles.Where(d => d.Pagado == false).Sum(dv => dv.Monto);
            //        var newTotalCredito = Math.Round(totalCredito, 2);
            //        lblTotalCredito.Text = newTotalCredito.ToString();
            //    }

            //    if (_pagos.Count > 0 && _detalles.Count > 0)
            //    {
            //        saldoFavor = _pagos.Sum(dv => dv.Monto) - (_detalles.Where(dv => dv.Pagado == true).Sum(d => d.Monto));
            //        lblSaldoFavor.Text = saldoFavor.ToString();

            //        var lDeuda = totalCredito - saldoFavor;
            //        if (lDeuda > 0)
            //        {
            //            lblDeuda.Text = lDeuda.ToString();
            //        }
            //        else lblDeuda.Text = "0.00";
            //    }
            //    else
            //    {
            //        lblSaldoFavor.Text = "0.00";
            //        lblDeuda.Text = totalCredito.ToString();
            //    }
            //}
        }

        private void cREDITODataGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            var _credito = cREDITOBindingSource.Current as CREDITO;
            if (_credito != null)
            {
                var _detalles = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", _credito.Id);
                dETALLE_CREDITOBindingSource.DataSource = _detalles;

                var _pagos = pagoBL.GetFromPagosbyCreditoId(_credito.Id);
                dETALLEPAGOesBindingSource.DataSource = _pagos;

                decimal saldoFavor = 0;
                decimal totalCredito = 0;

                if (_pagos != null)
                {
                    var totalPagos = _pagos.Sum(p => p.Monto);
                    var newTotalPagos = Math.Round(totalPagos, 2);
                    lblTotalPagos.Text = newTotalPagos.ToString();
                }

                if (_detalles != null)
                {
                    totalCredito = _detalles.Where(d => d.Pagado == false).Sum(dv => dv.Monto);
                    var newTotalCredito = Math.Round(totalCredito, 2);
                    lblTotalCredito.Text = newTotalCredito.ToString();

                    saldoFavor = _pagos.Sum(dv => dv.Monto) - (_detalles.Where(dv => dv.Pagado == true).Sum(d => d.Monto));

                    var lDeuda = totalCredito - saldoFavor;
                    if (lDeuda > 0)
                    {
                        lblDeuda.Text = lDeuda.ToString();
                    }
                    else lblDeuda.Text = "0.00";
                }

                if (_pagos.Count > 0 && _detalles.Count > 0)
                {
                    saldoFavor = _pagos.Sum(dv => dv.Monto) - (_detalles.Where(dv => dv.Pagado == true).Sum(d => d.Monto));
                    lblSaldoFavor.Text = saldoFavor.ToString();

                    var lDeuda = totalCredito - saldoFavor;
                    if (lDeuda > 0)
                    {
                        lblDeuda.Text = lDeuda.ToString();
                    }
                    else lblDeuda.Text = "0.00";
                }
                else
                {
                    lblDeuda.Text = totalCredito.ToString();
                    lblSaldoFavor.Text = "0.00";
                    //lblDeuda.Text = "0.00";
                }
                //CargarMontos();////////////
            }
            else
            {
                dETALLE_CREDITOBindingSource.Clear();
                dETALLEPAGOesBindingSource.Clear();
                lblTotalPagos.Text = "0.00"; 
                lblTotalCredito.Text = "0.00";
                lblSaldoFavor.Text = "0.00";
                lblDeuda.Text = "0.00";
            }
        }

        private void cREDITODataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            #region NuevoPago
            if (this.cREDITODataGridView.Columns[e.ColumnIndex].Name.Equals("nuevoPago"))
            {
                var currentCredito = cREDITOBindingSource.Current as CREDITO;

                var pagosAntes = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);

                frmPagos frm = new frmPagos();
                frm.nuevoPago(currentCredito.Id, currentCredito.clienteId);
                frm.ShowDialog();

                //decimal count = 0;
                decimal montoUltimoPago = 0;
                decimal saldoFavor = 0;

                if (currentCredito != null)
                {
                    var pagosDespues = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);
                    var detalles = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);

                    if (pagosAntes.Count < pagosDespues.Count)
                    {
                        montoUltimoPago = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id).LastOrDefault().Monto;
                    }
                    if (pagosDespues.Count > 0 && detalles.Count > 0)
                    {
                        var a = pagosDespues.Sum(dv => dv.Monto);
                        var b = detalles.Where(dv => dv.Pagado == true).Sum(d => d.Monto);
                        saldoFavor = (a - b) - montoUltimoPago;

                        lblSaldoFavor.Text = saldoFavor.ToString();
                        montoUltimoPago = montoUltimoPago + saldoFavor;

                        dETALLEPAGOesBindingSource.DataSource = pagosDespues;

                        foreach (var item in detalles.Where(d => d.Pagado == false).OrderBy(d => d.Monto))
                        {
                            if (item.Monto <= montoUltimoPago)
                            {
                                detalleCredBL.UpdateDetalleCreditoByCreditoIdAndDetalleId(currentCredito.Id, item.id);
                                montoUltimoPago = montoUltimoPago - item.Monto;
                            }
                            lblSaldoFavor.Text = montoUltimoPago.ToString();
                        }
                    }

                }
                else
                    lblSaldoFavor.Text = "0.00";
            }
            #endregion

            #region PasarVentas
            if (this.cREDITODataGridView.Columns[e.ColumnIndex].Name.Equals("PasarVenta"))
            {
                var currentCredito = cREDITOBindingSource.Current as CREDITO;

                if (currentCredito != null)
                {
                    var detalles = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);

                    //var impuesto = impBL.GetAnImpuestoToBoleta();
                    var impuesto = impBL.GetFromImpuestoById(1);

                    Decimal TotalNuevaVenta = 0;
                    var ProdNoPasados = 0;
                    var detalleVenta = new DETALLEVENTA();

                    foreach (var item in detalles.Where(d => d.Pagado == true && d.PasadoVenta == false))  //foreach (var item in currentCredito.DETALLE_CREDITO)  //
                    {
                        TotalNuevaVenta = TotalNuevaVenta + item.Monto;
                    }

                    var nuevaVenta = new VENTA
                    {
                        Cancelada = false,
                        CLIENTE = currentCredito.CLIENTE,
                        ClienteId = currentCredito.clienteId,
                        Fecha = DateTime.Today.Date,
                        ImpuestoId = impuesto.Id,
                        Total = TotalNuevaVenta,
                        Factura = false,
                        IGV = impuesto.Porcentaje.ToString(),
                        Observacion = " "
                    };

                    foreach (var item in detalles.Where(d => d.Pagado == true && d.PasadoVenta == false).OrderBy(d => d.FechaDetalleCredito))
                    {
                        ProdNoPasados++;
                        detalleVenta = new DETALLEVENTA
                        {
                            ProductoId = item.ProductoId,
                            PRODUCTO = item.PRODUCTO,
                            Cantidad = item.Cantidad,
                            Precio = item.Precio,
                        };
                        ////// Para controlar reducción de Stock en TRIGUER: ActualizarStock en DetalleVenta al Editar
                        var producto = prodBL.GetFromProductoById(item.ProductoId);
                        producto.Stock = producto.Stock + item.Cantidad;
                        prodBL.UpdateSoloProducto(producto);
                        /////
                        nuevaVenta.DETALLEVENTAs.Add(detalleVenta);
                        //cambiar estado de detalleCredito a pagado
                        detalleCredBL.PasarDetalleCreditoToVentaByIdAndCreditoId(item.id, currentCredito.Id);
                    }
                    if (ProdNoPasados > 0)
                    {
                        ventaBL.AddVenta(nuevaVenta);
                        MessageBox.Show("Productos del Crédito pasados a ventas", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                        MessageBox.Show("No existen productos sin pasar a ventas", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }


            #endregion

            #region Reporte
            if (this.cREDITODataGridView.Columns[e.ColumnIndex].Name.Equals("REPORTE"))
            {
                var _credito = cREDITOBindingSource.Current as CREDITO;

                var fec1 = _credito.FechaCredito.Date;

                if (_credito != null)
                {
                    //Reportes.frmDeudasCreditos frm = new Reportes.frmDeudasCreditos();
                    //frm.ObtenerFecha1(fec1.Date);
                    //frm.ObtenerFecha2(fec2.Date);
                    //frm.ObtenerCliente(_credito.CLIENTE.NombreRazonSocial);
                    //frm.Show();
                }
                else MessageBox.Show("Debe seleccionar un Crédito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            #endregion

            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditos();
            cREDITOBindingSource.ResetBindings(true);

        }

        private void txtCliente_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TodosLosBuscar();
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            frmMttoCredito frm = new frmMttoCredito();
            frm.Nuevo();
            frm.ShowDialog();
            cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditos();
            DesencadenarPago();
        }

        private void BtnUpdate_Click(object sender, EventArgs e)
        {
            var _credito = cREDITOBindingSource.Current as CREDITO;

            if (_credito != null)
            {
                frmMttoCredito frm = new frmMttoCredito();
                frm.Editar(_credito.Id);
                frm.ShowDialog();
                cREDITOBindingSource.DataSource = creditoBL.GetAllFromCreditos();
                DesencadenarPago();
            }
            else
            {
                MessageBox.Show("Debe seleccionar un Crédito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            

        }

        private void DesencadenarPago()
        {
            var allCreditos = creditoBL.GetAllFromCreditos();

            foreach (var _credito in allCreditos)
            {
                var currentCredito = _credito;
                //var currentCredito = cREDITOBindingSource.Current as CREDITO;

                decimal montoUltimoPago = 0;
                decimal saldoFavor = 0;

                if (currentCredito != null)
                {
                    var _pagos = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);
                    var detalles = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);

                    if (_pagos.Count >= 0 && detalles.Count > 0)
                    {
                        var a = _pagos.Sum(dv => dv.Monto);
                        var b = detalles.Where(dv => dv.Pagado == true).Sum(d => d.Monto);
                        saldoFavor = (a - b) - montoUltimoPago;

                        lblSaldoFavor.Text = saldoFavor.ToString();
                        montoUltimoPago = montoUltimoPago + saldoFavor;

                        dETALLEPAGOesBindingSource.DataSource = _pagos;

                        foreach (var item in detalles.Where(d => d.Pagado == false).OrderBy(d => d.Monto))
                        {
                            if (item.Monto <= montoUltimoPago)
                            {
                                detalleCredBL.UpdateDetalleCreditoByCreditoIdAndDetalleId(currentCredito.Id, item.id);
                                montoUltimoPago = montoUltimoPago - item.Monto;
                            }
                            lblSaldoFavor.Text = montoUltimoPago.ToString();
                        }
                    }

                }
                else
                    lblSaldoFavor.Text = "0.00";
            }
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            TodosLosBuscar();
        }

        public void TodosLosBuscar()
        {
            try
            {
                if (rbtnGeneral.Checked == true)
                {
                    CargarCreditoByCliente();
                }
                if (rbtnFecha.Checked == true)
                {
                    CargarCreditoByFechas();
                }
                if (rbtnAmbos.Checked == true)
                {
                    CargarCreditoByAmbos();
                }
                if (rbtnDia.Checked == true)
                {
                    CargarCreditoBySoloDia();
                }

                //var currentCredito = cREDITOBindingSource.Current as CREDITO;
                //{
                //    if (currentCredito != null)
                //    {
                //        dETALLE_CREDITOBindingSource.DataSource = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId("", currentCredito.Id);
                //        dETALLEPAGOesBindingSource.DataSource = pagoBL.GetFromPagosbyCreditoId(currentCredito.Id);
                        
                //        var totalDeuda = currentCredito.Total;
                //        var newtotalDeuda = Math.Round(totalDeuda, 2);
                //        lblTotalDeuda.Text = newtotalDeuda.ToString();       
                //    }
                //    else
                //    {
                //        dETALLE_CREDITOBindingSource.Clear();
                //        dETALLEPAGOesBindingSource.Clear();
                        
                //    }
                //}


            }
            catch (Exception)
            {
                MessageBox.Show("No existen créditos registrados", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public void CargarCreditoByFechas()
        {
            lblDesde.Text = "Desde:";
            lblHasta.Visible = true;
            dateTimePicker2.Visible = true;
            var fec1 = dateTimePicker1.Value.Date;
            var fec2 = dateTimePicker2.Value.Date;
            if (fec1 <= fec2)
            {
                cREDITOBindingSource.DataSource = creditoBL.GetFromCreditobyFechaAndCliente(fec1, fec2, "");
            }
            else
            {
                ReiniciarFechas();
                MessageBox.Show("La fecha de inicio debe ser menor a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public void CargarCreditoByCliente()
        {
            lblDesde.Text = "Desde:";
            lblHasta.Visible = true;
            dateTimePicker2.Visible = true;
            cREDITOBindingSource.DataSource = creditoBL.GetFromCreditobyCliente(txtCliente.Text);
        }

        public void CargarCreditoByAmbos()
        {
            lblDesde.Text = "Desde:";
            lblHasta.Visible = true;
            dateTimePicker2.Visible = true;
            var fec1 = dateTimePicker1.Value.Date;
            var fec2 = dateTimePicker2.Value.Date;
            if (fec1 <= fec2)
            {
                cREDITOBindingSource.DataSource = creditoBL.GetFromCreditobyFechaAndCliente(fec1, fec2, txtCliente.Text);
            }
            else
            {
                ReiniciarFechas();
                MessageBox.Show("La fecha de inicio debe ser menor a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public void CargarCreditoBySoloDia()
        {
            lblDesde.Text = "Día:";
            lblHasta.Visible = false;
            dateTimePicker2.Visible = false;
            var fec1 = dateTimePicker1.Value.Date;
            cREDITOBindingSource.DataSource = creditoBL.GetFromCreditobyFechaAndCliente(fec1, null, txtCliente.Text);
        }      

        private void rbtnGeneral_Click(object sender, EventArgs e)
        {
            txtCliente.Enabled = true;
            txtCliente.ReadOnly = false;
            dateTimePicker1.Enabled = false;
            dateTimePicker2.Enabled = false;
            CargarCreditoByCliente();
        }

        private void rbtnFecha_Click(object sender, EventArgs e)
        {
            txtCliente.ReadOnly = true;
            dateTimePicker1.Enabled = true;
            dateTimePicker2.Enabled = true;
            CargarCreditoByFechas();
        }

        private void rbtnAmbos_Click(object sender, EventArgs e)
        {
            txtCliente.Enabled = true;
            txtCliente.ReadOnly = false;
            dateTimePicker1.Enabled = true;
            dateTimePicker2.Enabled = true;
            CargarCreditoByAmbos();
        }

        private void rbtnDia_Click(object sender, EventArgs e)
        {
            txtCliente.Enabled = true;
            txtCliente.ReadOnly = false;
            dateTimePicker1.Enabled = true;
            CargarCreditoBySoloDia();
        }

        private void TxtProductoDesc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BuscarEnDetalleCredito();
            }
        }

        private void BtnBuscarProducto_Click(object sender, EventArgs e)
        {
            BuscarEnDetalleCredito();
        }

        private void BuscarEnDetalleCredito()
        {
            CREDITO _currentCredito = cREDITOBindingSource.Current as CREDITO;
            if (_currentCredito != null)
            {
                dETALLE_CREDITOBindingSource.DataSource = detalleCredBL.GetFromDetalleCreditoByProductoDescAndCreditoId(TxtProductoDesc.Text, _currentCredito.Id);
            }
            else
            {
                MessageBox.Show("Debe seleccionar un Crédito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //private DateTime fec1 = DateTime.Now.Date;
        private DateTime fec2 = DateTime.Now.Date;

        private void btnReporte_Click(object sender, EventArgs e)
        {
            var _credito = cREDITOBindingSource.Current as CREDITO;

            var fec1 = _credito.FechaCredito.Date;

            if (_credito != null)
            {
                //Reportes.frmDeudasCreditos frm = new Reportes.frmDeudasCreditos();

                //frm.ObtenerFecha1(fec1.Date);
                //frm.ObtenerFecha2(fec2.Date.AddDays(7));
                //frm.ObtenerCliente(_credito.CLIENTE.NombreRazonSocial);
                //frm.ShowDialog();

            }
            else MessageBox.Show("Debe seleccionar un Crédito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

      

    }
}
